package point

import (
	"fmt"
	"os/exec"
	"strings"
)

type TimeZonePoint struct {
	timeZoneMap map[string]string
}

const timeZonePath = "/usr/share/zoneinfo/"

func NewTimeZonePoint() *TimeZonePoint {
	return &TimeZonePoint{
		timeZoneMap: map[string]string{
			"UTC":     timeZonePath + "Etc/GMT",
			"UTC+0":   timeZonePath + "Etc/GMT-0",
			"UTC-0":   timeZonePath + "Etc/GMT+0",
			"UTC+1":   timeZonePath + "Etc/GMT-1",
			"UTC-1":   timeZonePath + "Etc/GMT+1",
			"UTC+2":   timeZonePath + "Etc/GMT-2",
			"UTC-2":   timeZonePath + "Etc/GMT+2",
			"UTC+3":   timeZonePath + "Etc/GMT-3",
			"UTC-3":   timeZonePath + "Etc/GMT+3",
			"UTC+3.5": timeZonePath + "Asia/Tehran",
			"UTC+4":   timeZonePath + "Etc/GMT-4",
			"UTC-4":   timeZonePath + "Etc/GMT+4",
			"UTC+5":   timeZonePath + "Etc/GMT-5",
			"UTC+5.5": timeZonePath + "Asia/Kolkata",
			"UTC-5":   timeZonePath + "Etc/GMT+5",
			"UTC+6":   timeZonePath + "Etc/GMT-6",
			"UTC-6":   timeZonePath + "Etc/GMT+6",
			"UTC+7":   timeZonePath + "Etc/GMT-7",
			"UTC-7":   timeZonePath + "Etc/GMT+7",
			"UTC+8":   timeZonePath + "Etc/GMT-8",
			"UTC-8":   timeZonePath + "Etc/GMT+8",
			"UTC+9":   timeZonePath + "Etc/GMT-9",
			"UTC-9":   timeZonePath + "Etc/GMT+9",
			"UTC+10":  timeZonePath + "Etc/GMT-10",
			"UTC-10":  timeZonePath + "Etc/GMT+10",
			"UTC+11":  timeZonePath + "Etc/GMT-11",
			"UTC-11":  timeZonePath + "Etc/GMT+11",
			"UTC+12":  timeZonePath + "Etc/GMT-12",
			"UTC-12":  timeZonePath + "Etc/GMT+12",
		},
	}
}

func (s *TimeZonePoint) Get() any {
	getTimeZone := func() string {
		cmd := exec.Command("ls", "-alsh", "/etc/localtime")
		out, err := cmd.Output()
		if err != nil {
			return ""
		}

		res := strings.Fields(strings.TrimSuffix(string(out), "\n"))

		if len(res) == 0 {
			return ""
		}

		return res[len(res)-1]
	}

	zone := getTimeZone()

	for k, v := range s.timeZoneMap {
		if v == zone {
			return k
		}
	}

	return ""

}

func (s *TimeZonePoint) Set(val ...any) bool {
	if len(val) < 1 {
		fmt.Println("set val error")
		return false
	}

	setTimeZone := func(tz string) bool {
		location, ok := s.timeZoneMap[tz]
		if !ok {
			return false
		}

		return exec.Command("sudo", "ln", "-sf", location, "/etc/localtime").Run() == nil
	}

	if timeZone, ok := val[0].(string); ok {
		return setTimeZone(timeZone)
	}

	return false
}

func (s *TimeZonePoint) SetRoute(string) PointInterface { return s }
